#-*-coding:utf-8-*-#

import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

currentPath = os.getcwd()
os.chdir('PATH')

D = pd.read_csv('Data_Fig1c_1.csv') # Wildfire Twitter data with sentiment analysis

wfindex = pd.read_csv('Data_Fig1c_2.csv') # US wildfire index data
ref = pd.read_csv('Data_Fig1c_3.csv') # dates of 2012 March-December

D['Date'] = pd.to_datetime(D['Date'], errors='coerce')
D['Date'] = D['Date'].dt.strftime("%Y-%m-%d")
dates = D['Date'].drop_duplicates()
dates= dates.sort_values()
dates= dates.reset_index(drop=True)
dates = dates.dropna()

D = D[D['polarity']=='negative']
D1 = D[~D['Retweet_to'].isna()]
D2 = D[~D['Reply_to'].isna()]

D = pd.concat([D1,D2])

dr_date = pd.DataFrame()
dr_date['Date'] = dates
dr_date['positive'] = 0
dr_date['negative'] = 0
dr_date['neutral'] = 0

for i in range(len(dates)):
    total = D[D['Date']== dates[i]]
    polar = total.groupby(['polarity']).count()
    for j in range(len(polar)):
        dr_date[polar.index[j]].iloc[i]= polar['Date'][polar.index[j]]

wfindex.columns = ['latitude','longitude','brightness','scan','track','acq_date',
               'acq_time','satellite','instrument','confidence','version',
               'bright_t31','frp','daynight','type']

wfindex = wfindex[(wfindex['latitude']<=50)&(wfindex['longitude']>=-126)]

ref['Date'] = pd.to_datetime(ref['Date'], errors='coerce')
ref['Date'] = ref['Date'].dt.strftime("%Y-%m-%d")
dates = ref['Date'].drop_duplicates()
dates= dates.sort_values()
dates= dates.reset_index(drop=True)
dates = dates.dropna()

wff = pd.DataFrame()
wff['Date'] = dates
wff['freq'] = 0
z=0

wff['Date']= pd.to_datetime(wff['Date'], errors='coerce')
wff['Date'] = wff['Date'].dt.strftime("%Y-%m-%d")

wfindex = wfindex[wfindex['type'] == 0]
wfindex = wfindex[wfindex['confidence'] >= 95]
wfindex = wfindex.reset_index(drop=True)


dt12 = wff
dt12 = dt12.reset_index(drop=True)

# From 2012 March
dt12 = dt12[60:]
dt12 = dt12.reset_index(drop=True)

fig, ax1 = plt.subplots(dpi=400,figsize=(6,2))
ax1.set_ylabel('Fire Detections (x100)')
ax1.set_yticklabels([0,'0','2.5','5','7.5','10'])
ax1.axhline(y=0,linestyle='dotted',color='k')
ax1.axhline(y=250,linestyle='dotted',color='k')
ax1.axhline(y=500,linestyle='dotted',color='k')
ax1.axhline(y=750,linestyle='dotted',color='k')
ax1.axhline(y=1000,linestyle='dotted',color='k')
ax1.set_xticks(range(0,len(dt12),60))
ax1.set_xlim([0,len(dt12)])
line1 = ax1.plot(wff['Date'][4077:],wff['freq'][4077:],color='black',linewidth=1)

ax2 = ax1.twinx()
ax2.set_ylabel('Twitter',color='blue',rotation=270,va='bottom')
line2 = ax2.plot(dr_date['Date'],dr_date['negative'],color='blue',linewidth=1.0)
ax2.tick_params(axis='y', labelcolor='blue')
plt.tight_layout()
lines=line1 + line2
plt.show()
